//
//  YYNavigationItem.m
//  YYNavigationBar
//
//  Created by yangyang on 16/8/1.
//  Copyright © 2016年 机智的静默( http://www.cnblogs.com/jingmo/ ). All rights reserved.
//

#import "YYNavigationItem.h"
#import "YYNavigationMacro.h"
#import "UIView+YYNavigationFrame.h"
#import "NSObject+YYHelper.h"

@interface YYNavigationItem ()

@property (nonatomic, weak) UIViewController *lastVC;

@property (nonatomic) UIImageView *separatorLine;
@property (nonatomic) UILabel *titleLabel;

@end

@implementation YYNavigationItem

#pragma mark - InitMethod

+ (instancetype)naviItemWithStackCount:(CGFloat)stackCount lastViewController:(UIViewController *)lastViewController {
    YYNavigationItem *navigationItem = [[YYNavigationItem alloc] initWithStackCount:stackCount lastViewController:lastViewController];
    return navigationItem;
}

- (instancetype)initWithStackCount:(CGFloat)stackCount lastViewController:(UIViewController *)lastViewController {
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, [NSObject yy_statusBarHeight], [NSObject yy_naviBarWidth], 44);
        // 防止触发setter方法
        _textColor = [UIColor whiteColor];
        // 自动添加标题label
        [self addSubview:self.titleLabel];
        // 自动添加分割线
        [self addSubview:self.separatorLine];
        // 如果栈个数大于1，自动添加返回按钮
        _backImage = [self yy_getImageWithBundleName:@"YYNavigation" imageName:@"back"];
        @weakify(self);
        self.backButton = [YYNavigationBarButton buttonWithImage:_backImage handler:^(UIButton *sender) {
            @strongify(self);
            [self popViewController];
        }];
        if (stackCount < 2) {
            self.isHiddenBackButton = YES;
        }
        
        self.lastVC = lastViewController;
    }
    
    return self;
}

#pragma mark - Public Method

- (void)refreshSubLayout {
    // 如果存在titleview，则直接返回
    if (self.titleView) {
        return;
    }
    
    // 如果存在返回按钮，则处理返回按钮位置
    // 如果不存在返回按钮且存在左侧按钮集合，则处理左侧按钮集合
    if (!self.backButton.hidden) {
        self.backButton.X = YYSpace;
        self.backButton.Y = (self.height - _backButton.height) / 2;
    } else if (self.leftButtons) {
        __block CGFloat left = YYSpace;
        [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.X = left;
            obj.Y = (self.height - obj.height) / 2;
            left += obj.width + YYSpace;
        }];
    }
    
    // 如果存在标题栏，则处理标题栏
    if (self.title.length > 0) {
        [self.titleLabel sizeToFit];
        self.titleLabel.Y = 0;
        self.titleLabel.height = self.height;
        self.titleLabel.centerX = self.centerX;
    }
    
    // 如果存在右侧按钮集合，则处理右侧按钮集合
    __block CGFloat right = YYSpace;
    [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        right += obj.width;
        obj.X = self.width - right;
        obj.Y = (self.height - obj.height) / 2;
        right += YYSpace;
    }];
}

#pragma mark - SetterMethod

- (void)setTitle:(NSString *)title {
    _title = title;
    if (self.titleView) {
        return;
    }
    self.titleLabel.hidden = NO;
    self.titleLabel.text = title;
    [self.titleLabel sizeToFit];
    
    self.titleLabel.Y = 0;
    self.titleLabel.height = self.height;
    self.titleLabel.centerX = self.centerX;
}

- (void)setTitleView:(UIView *)titleView {    
    // 如果titlelabel存在父视图，移除置空
    if (self.titleLabel) {
        self.titleLabel.hidden = YES;
    }
    
    // 如果存在返回按钮，移除
    if (self.backButton) {
        [self.backButton removeFromSuperview];
    }
    
    // 如果存在左侧按钮集合，移除
    [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    _leftButtons = nil;
    
    // 如果存在右侧按钮集合，移除
    [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    _rightButtons = nil;
    
    // 如果已经设置了，移除旧的
    [_titleView removeFromSuperview];
    // 添加新的
    _titleView = titleView;
    [self addSubview:_titleView];
    
    // 如果没设置宽高，则覆盖整个navigationItem
    if (_titleView.width == 0 || _titleView.height == 0) {
        [titleView setFrame:CGRectMake(0, 0, self.width, self.height)];
    }
}

- (void)setTextColor:(UIColor *)textColor {
    if (self.titleView) {
        return;
    }
    _textColor = textColor;
    
    self.titleLabel.textColor = textColor;
    
    [self.backButton setTitleColor:textColor forState:UIControlStateNormal];

    [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitleColor:textColor forState:UIControlStateNormal];
//        obj.tintColor = textColor;
    }];
    
    [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setTitleColor:textColor forState:UIControlStateNormal];
//        obj.tintColor = textColor;
    }];
}

- (void)setButtonImageColor:(UIColor *)buttonImageColor {
    if (!buttonImageColor || buttonImageColor == [UIColor clearColor]) {
        [self.backButton setImage:[self.backImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];

        [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }];
        
        [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }];
    } else {
        [self.backButton setImage:[self.backImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        self.backButton.tintColor = buttonImageColor;

        [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
            obj.tintColor = buttonImageColor;
        }];
        
        [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
            obj.tintColor = buttonImageColor;
        }];
    }
}

- (void)setTextFont:(UIFont *)textFont {
    if (self.titleView) {
        return;
    }
    _textFont = textFont;
    self.titleLabel.font = textFont;
    [self.titleLabel sizeToFit];
    self.titleLabel.Y = 0;
    self.titleLabel.height = self.height;
    self.titleLabel.centerX = self.centerX;
    
    self.backButton.titleLabel.font = textFont;
    [self.backButton refreshSize];
    
    __block CGFloat left = YYSpace;
    [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.titleLabel.font = textFont;
        [obj refreshSize];
        obj.X = left;
        obj.Y = (self.height - obj.height) / 2;
        left += obj.width + YYSpace;
    }];
    
    __block CGFloat right = YYSpace;
    [self.rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.titleLabel.font = self.textFont ? self.textFont : [UIFont systemFontOfSize:YYButtonFont];
        [obj refreshSize];
        right += obj.width;
        obj.X = self.width - right;
        obj.Y = (self.height - obj.height) / 2;
        right += YYSpace;
    }];
}

- (void)setSeparatorLineColor:(UIColor *)separatorLineColor {
    _separatorLineColor = separatorLineColor;
    
    self.separatorLine.image = nil;
    self.separatorLine.backgroundColor = separatorLineColor;
    
    if (!self.separatorLine.superview) {
        [self addSubview:self.separatorLine];
    }
}

- (void)setSeparatorLineImage:(UIImage *)separatorLineImage {
    _separatorLineImage = separatorLineImage;
    
    self.separatorLine.backgroundColor = [UIColor clearColor];
    self.separatorLine.image = separatorLineImage;
    
    if (!self.separatorLine.superview) {
        [self addSubview:self.separatorLine];
    }
}

- (void)setLeftButtons:(NSArray<YYNavigationBarButton *> *)leftButtons {
    // 如果存在返回按钮，则隐藏
    if (self.backButton) {
        self.backButton.hidden = YES;
    }
    // 如果存在titleView，则隐藏
    if (self.titleView) {
        self.titleView.hidden = YES;
    }
    // 如果存在旧的左侧按钮，则移除旧的
    [_leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    // 调整位置，并添加显示
    _leftButtons = leftButtons;
    __block CGFloat left = YYSpace;
    [_leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.titleLabel.font = self.textFont ? self.textFont : [UIFont systemFontOfSize:YYButtonFont];
        [obj refreshSize];
        obj.X = left;
        obj.Y = (self.height - obj.height) / 2;
        if (self.buttonImageColor) {
            obj.tintColor = self.buttonImageColor;
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        } else {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
        [obj setTitleColor:self.textColor forState:UIControlStateNormal];
        [self addSubview:obj];
        left += obj.width + YYSpace;
    }];
    // 调整titleLabel
    self.title = self.titleLabel.text;
}

- (void)setRightButtons:(NSArray<YYNavigationBarButton *> *)rightButtons {
    // 如果存在titleView，则移除
    if (self.titleView) {
        [self.titleView removeFromSuperview];
    }
    // 如果存在旧的右侧按钮，则移除旧的
    [_rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    // 调整位置，并添加显示
    _rightButtons = rightButtons;
    __block CGFloat right = YYSpace;
    [_rightButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.titleLabel.font = self.textFont ? self.textFont : [UIFont systemFontOfSize:YYButtonFont];
        [obj refreshSize];
        right += obj.width;
        obj.X = self.width - right;
        obj.Y = (self.height - obj.height) / 2;
        if (self.buttonImageColor) {
            obj.tintColor = self.buttonImageColor;
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        } else {
            [obj setImage:[obj.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
        [obj setTitleColor:self.textColor forState:UIControlStateNormal];
        [self addSubview:obj];
        right += YYSpace;
    }];
    
    // 调整titleLabel
    self.title = self.titleLabel.text;
}

- (void)setBackButton:(YYNavigationBarButton *)backButton {
    // 如果之前的返回按钮存在，从先移除旧的返回按钮
    if (_backButton.superview) {
        [_backButton removeFromSuperview];
    }
    
    // 如果有左侧按钮集合，移除并清空
    if (self.leftButtons.count > 0) {
        [self.leftButtons enumerateObjectsUsingBlock:^(YYNavigationBarButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        _leftButtons = nil;
    }
    
    _backButton = backButton;
    if (self.buttonImageColor) {
        [_backButton setImage:[self.backImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        _backButton.tintColor = self.buttonImageColor;
    }
    [_backButton setTitleColor:self.textColor forState:UIControlStateNormal];
    _backButton.titleLabel.font = self.textFont ? self.textFont : [UIFont systemFontOfSize:YYButtonFont];
    [_backButton refreshSize];
    [self addSubview:_backButton];
    
    // 布局返回按钮位置
    CGFloat y = (self.height - _backButton.height) / 2;
    _backButton.X = YYSpace;
    _backButton.Y = y;
 
    // 显示返回按钮，并调整titleview或者titlelabel位置
    self.isHiddenBackButton = NO;
}

- (void)setBackImage:(UIImage *)backImage {
    _backImage = backImage;
    if (self.buttonImageColor) {
        self.backButton.tintColor = self.buttonImageColor;
    }
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    [self.backButton sizeToFit];
    self.backButton.width = self.backButton.width + 3;
    
    // 布局返回按钮位置
    CGFloat y = (self.height - _backButton.height) / 2;
    _backButton.X = YYSpace;
    _backButton.Y = y;
}

- (void)setIsHiddenBackButton:(BOOL)isHiddenBackButton {
    _isHiddenBackButton = isHiddenBackButton;
    self.backButton.hidden = isHiddenBackButton;
    if (isHiddenBackButton) {
        // 如果存在titleView，调整titleView的X
        if (self.titleView) {
            CGFloat y = (self.height - self.titleView.height) / 2;
            self.titleView.frame = CGRectMake(0, y, self.titleView.width, self.titleView.height);
        }
    } else {
        CGFloat leftX = YYSpace + _backButton.width + YYSpace;
        // 如果存在titleView，调整titleView的X
        if (self.titleView) {
            CGFloat y = (self.height - self.titleView.height) / 2;
            self.titleView.frame = CGRectMake(leftX, y, self.titleView.width - leftX, self.titleView.height);
        }
    }
    // 调整titleLabel
    self.title = self.titleLabel.text;
}

#pragma mark - Getter

- (UIImageView *)separatorLine {
    if (!_separatorLine) {
        _separatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.height - 1.0, self.width, 1.0)];
        _separatorLine.backgroundColor = [UIColor clearColor];
    }
    return _separatorLine;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.text = @"";
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont systemFontOfSize:YYLabelFont];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

#pragma mark - Back Action

- (void)popViewController {
    [self.lastVC.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Private Method

- (UIImage *)yy_getImageWithBundleName:(NSString *)bundleName imageName:(NSString *)imageName {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *url = [bundle URLForResource:bundleName withExtension:@"bundle"];
    NSBundle *resourceBundle = [NSBundle bundleWithURL:url];
    if (resourceBundle) {
        return [UIImage imageNamed:imageName inBundle:resourceBundle compatibleWithTraitCollection:nil];
    } else {
        return nil;
    }
}

@end
